package com.example.javamaday.leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.PriorityQueue;

public class LeetCodeTest0347 {

    public static void main(String[] args) {

    }

    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> numberMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer value = numberMap.get(nums[i]);
            if (value == null) {
                numberMap.put(nums[i], 1);
            } else {
                numberMap.put(nums[i], value + 1);
            }
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer t1, Integer t2) {
                return numberMap.get(t2).compareTo(numberMap.get(t1));
            }
        });
        for (Integer integer : numberMap.keySet()) {
            priorityQueue.offer(integer);
        }

        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = priorityQueue.poll();
        }

        return result;
    }
}
